const {Task} = require('@/mysql/task')
const {Project} = require('@/mysql/project')
const {UserProject} = require('@/mysql/user_project')
/** 查找查看项目所有任务 */
const getAllTask = async ctx => {
    const project_id = ctx.params.id
    const data =await Task.getAllTasks(project_id)
    ctx.body = data
}

/** 添加任务 */
const insertTask = async ctx => {
    if (ctx.request.body) {
        //步骤——————》 表单验证，判断是否存在项目，判断该项目是不是属于用户，允许插入
        const project_id = ctx.params.id
        let {name, description, forUser, expire_time} = ctx.request.body
        if (!project_id) return ctx.response.body = global.toJson(1, `缺少任务Id`)
        if (!name) return ctx.response.body = global.toJson(1, `缺少任务名称`)
        if (!forUser) return ctx.response.body = global.toJson(1, `缺少任务执行人`)
        if (!expire_time) return ctx.response.body = global.toJson(1, `缺少任务过期时间`)
        const projects = await Project.findById(project_id);
        if (projects.length === 0) return ctx.response.body = global.toJson(1, `没有找到该项目`)
        const userInfo = await UserProject.findByProjectId(project_id)
        if(userInfo.length === 0) return ctx.response.body = global.toJson(1, `该项目没有归属人，不能进行操作`)
        if(global.utils.getUserId() !== Number(userInfo[0].user_id))  return ctx.response.body = global.toJson(1, `没有权限操作该项目`)
        const data = await Task.insertData(project_id, name, description, forUser, expire_time)
        if (data) {
            ctx.response.body = global.toJson(0, '添加任务成功')
        }
    }
}
// 修改任务
const updateTask = async ctx => {
    const params = ctx.request.body
    if(params) {
        let {name, description, id, forUser, expire_time} = params
        console.log(params)
        const data = await Task.updateData(id,name,description, expire_time, forUser)
        if(data.length !== 0) ctx.body = global.toJson(0, `修改任务完成`)
    }
}

const removeTask = async ctx => {
    const removeId = ctx.params.id
    if(!removeId) ctx.body = global.toJson(1, `没有任务Id,无法删除`)
   const data =  await Task.update({
        deleted: true
    },{where:{id:removeId}})
    if(data.length !== 0) ctx.body = global.toJson(0, '删除成功')
}

const updateTaskStatus = async ctx => {
    const {status, id} = ctx.request.body;
    if(!status) return ctx.body = global.toJson(1, '修改任务状态参数缺失')
    if(!id) return ctx.body = global.toJson(1, '修改任务状态Id缺失')
     await Task.update({
        status
    }, {where: {id}})
    return ctx.body = global.toJson(0, '修改任务状态成功')
}

export {getAllTask, insertTask, updateTask, removeTask, updateTaskStatus}
